<?php
	include('functions.php');
	date_default_timezone_set('Europe/Copenhagen');	
	$runs = 10;
	
	// index('posts', array('rating' => 1));
	// sleep(5);
	
	// construct map and reduce functions
	$map = new MongoCode("function() { emit(this.rating,1); }");
	$reduce = new MongoCode("function(k, vals) { ".
		"var sum = 0;".
		"for (var i in vals) {".
			"sum += vals[i];". 
		"}".
		"return sum; }");
	$posts = $conn->command(array(
		"mapreduce" => 'posts', 
		"map" => $map,
		"reduce" => $reduce,
		'out'	=> '_id'
	));

$time = array();
for($i=0; $i<$runs; $i++) {
	set_time_limit(0);
	ini_set("memory_limit","500M");
	$start = timeit();
		$ratings = $conn->selectCollection($posts['result'])->find()->explain();
		var_dump($ratings); exit;
	$end = timeit();
	$time[] = number_format($end - $start, 15);
	
	// If using this code, we drop (remove) the temporary mapreduce collection. 
	// Has been used for internal tests only
	//$conn->_id->drop();
}

l(avg($time));
unset($time);

foreach ($ratings as $rating) {
    echo "{$rating['value']} posts has rating: {$rating['_id']} <br />";
}

echo "done";

?>